#!/bin/bash
set -e

# ================== 配置区 ==================

short_to_maven_path() {
    case "$1" in
        hx-module-device)           echo "hx-module/hx-module-device" ;;
        hx-module-files)            echo "hx-module/hx-module-files" ;;
        hx-module-gateway)          echo "hx-module/hx-module-gateway" ;;
        hx-module-mqtt)             echo "hx-module/hx-module-mqtt" ;;
        hx-module-rabbitmq)         echo "hx-module/hx-module-rabbitmq" ;;
        hx-module-statisticalanalysis) echo "hx-module/hx-module-statisticalanalysis" ;;
        hx-module-system)           echo "hx-module/hx-module-system" ;;
        hx-module-websocket)        echo "hx-module/hx-module-websocket" ;;
        hx-module-workorder)        echo "hx-module/hx-module-workorder" ;;
        *)                          echo "" ;;
    esac
}

short_to_image_repo() {
    case "$1" in
        hx-module-device)           echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-device" ;;
        hx-module-files)            echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-files" ;;
        hx-module-gateway)          echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-gateway" ;;
        hx-module-mqtt)             echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-mqtt" ;;
        hx-module-rabbitmq)         echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-rabbitmq" ;;
        hx-module-statisticalanalysis) echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-statisticalanalysis" ;;
        hx-module-system)           echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-system" ;;
        hx-module-websocket)        echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-websocket" ;;
        hx-module-workorder)        echo "registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-workorder" ;;
        *)                          echo "" ;;
    esac
}

DOCKER_USERNAME="即停科技"
DOCKER_PASSWORD="juan8023"

# 重试配置
MAX_RETRIES=3
RETRY_DELAY=5  # 秒

# 通用重试函数
retry_command() {
    local cmd="$1"
    local description="$2"
    local attempt=1

    while [ $attempt -le $MAX_RETRIES ]; do
        echo "   🔁 [$attempt/$MAX_RETRIES] 尝试 $description..."
        if eval "$cmd"; then
            echo "   ✅ $description 成功"
            return 0
        fi
        if [ $attempt -lt $MAX_RETRIES ]; then
            echo "   ⏳ 失败，$RETRY_DELAY 秒后重试..."
            sleep $RETRY_DELAY
        fi
        attempt=$((attempt + 1))
    done

    echo "❌ $description 失败超过 $MAX_RETRIES 次，放弃。"
    exit 1
}

# ============================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR/../.."
PROJECT_ROOT="$(cd "$PROJECT_ROOT" && pwd)"

echo "📁 项目根目录: $PROJECT_ROOT"

if [ ! -f "$PROJECT_ROOT/pom.xml" ] || [ ! -d "$PROJECT_ROOT/hx-module" ]; then
    echo "❌ 错误：未在 $PROJECT_ROOT 找到 Maven 多模块项目的根目录结构！"
    echo "   请确保脚本位于 general/script/sh/ 下，且 general/ 是项目根目录。"
    exit 1
fi

cd "$PROJECT_ROOT"

ALL_SHORT_MODULES=(
    hx-module-device
    hx-module-files
    hx-module-gateway
    hx-module-mqtt
    hx-module-rabbitmq
    hx-module-statisticalanalysis
    hx-module-system
    hx-module-websocket
    hx-module-workorder
)

MODULES_TO_BUILD_SHORT=()

if [ $# -eq 0 ]; then
    echo "🚀 开始构建所有模块..."
    MODULES_TO_BUILD_SHORT=("${ALL_SHORT_MODULES[@]}")
else
    echo "🚀 开始构建指定模块: $*"
    for short_name in "$@"; do
        repo=$(short_to_image_repo "$short_name")
        if [ -z "$repo" ]; then
            echo "❌ 未知模块: $short_name"
            echo "   支持的模块有："
            printf "     - %s\n" "${ALL_SHORT_MODULES[@]}"
            exit 1
        fi
        MODULES_TO_BUILD_SHORT+=("$short_name")
    done
fi

# 使用统一的时间戳（所有模块共享同一时间，保证一致性）
BUILD_TIME_TAG=$(date +%Y%m%d%H%M)
echo "🕒 本次构建使用统一时间戳作为镜像 tag: $BUILD_TIME_TAG"

# 用于收集成功推送的镜像地址
declare -a PUSHED_IMAGES

# 先登录一次（避免每个模块都登录）
echo "🔑 首次登录阿里云镜像仓库..."
echo "$DOCKER_PASSWORD" | docker login registry.cn-shenzhen.aliyuncs.com --username "$DOCKER_USERNAME" --password-stdin

# 开始构建每个模块
for short_name in "${MODULES_TO_BUILD_SHORT[@]}"; do
    MAVEN_PATH=$(short_to_maven_path "$short_name")
    IMAGE_REPO=$(short_to_image_repo "$short_name")

    if [ -z "$MAVEN_PATH" ] || [ -z "$IMAGE_REPO" ]; then
        echo "❌ 内部错误：无法解析模块 $short_name"
        exit 1
    fi

    echo ""
    echo "──────────────────────────────────────────────"
    echo "📦 正在构建模块: $short_name"
    echo "   Maven 路径: $MAVEN_PATH"
    echo "   镜像仓库: $IMAGE_REPO"
    echo "   Tag: $BUILD_TIME_TAG"
    echo "──────────────────────────────────────────────"

    # 1. Maven 打包（带重试）
    MVN_CMD="mvn clean package -pl '$MAVEN_PATH' -am -DskipTests"
    retry_command "$MVN_CMD" "Maven 构建 ($short_name)"

    # 2. 检查 JAR
    APP_JAR_PATH="$MAVEN_PATH/target/app.jar"
    if [ ! -f "$APP_JAR_PATH" ]; then
        echo "❌ 未找到 app.jar！请确认 pom.xml 中配置了 spring-boot-maven-plugin 且 finalName 为 app"
        ls -l "$MAVEN_PATH/target/" 2>/dev/null || echo "   target 目录不存在"
        exit 1
    fi
    echo "   ✅ 找到 app.jar: $APP_JAR_PATH"

    FULL_IMAGE="$IMAGE_REPO:$BUILD_TIME_TAG"

    # 3. 构建镜像
    echo "   🐳 构建镜像: $FULL_IMAGE"
    docker build -t "$FULL_IMAGE" -f "$MAVEN_PATH/Dockerfile" "$MAVEN_PATH"

    # 4. 推送镜像（带重试）
    retry_command "docker push '$FULL_IMAGE'" "推送镜像 ($short_name)"

    echo "   ✅ 成功！镜像已推送至 $FULL_IMAGE"
    PUSHED_IMAGES+=("$FULL_IMAGE")
done

# ========== 最终输出：所有已推送镜像 ==========
echo ""
echo "🎉 所有模块构建并推送完成！"
echo ""
echo "📋 已推送的镜像列表（Tag = $BUILD_TIME_TAG，可直接复制用于 K3s deployment.yaml）："
echo "──────────────────────────────────────────────"
for img in "${PUSHED_IMAGES[@]}"; do
    echo "$img"
done
echo "──────────────────────────────────────────────"
echo ""
echo "💡 使用建议："
echo "   在你的 deployment.yaml 中，将 image 字段替换为上述对应镜像地址即可。"
echo "   例如："
echo "     spec:"
echo "       containers:"
echo "       - name: hx-module-system"
echo "         image: registry.cn-shenzhen.aliyuncs.com/ziyangk/hx-module-system:$BUILD_TIME_TAG"

# ========== 清理本地镜像 ==========
echo ""
echo "🧹 开始清理本地构建的镜像（释放磁盘空间）..."
for img in "${PUSHED_IMAGES[@]}"; do
    echo "   🗑️  删除本地镜像: $img"
    if docker rmi "$img" >/dev/null 2>&1; then
        echo "   ✅ 已删除: $img"
    else
        echo "   ⚠️  无法删除（可能已被其他 tag 引用）: $img"
    fi
done
echo "✅ 本地镜像清理完成！"